import strHtml from "./VideoPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { videoService } from "../../services/videoService";

export class VideoPage {
  constructor() {
    this.dom = null;
    this.videoList = [];
    this.table = null;
    this.videoModal = null;
    this.deleteConfirmModal = null;
    this.pendingDeleteId = null;
  }

  async render() {
    const html = strHtml;
    this.dom = DomUtils.convertToDom(html);

    this._bindEvents();
    await this._loadData();
    this._initDataTable();

    return this.dom;
  }

  async _loadData() {
    try {
      const res = await videoService.getAll();
      this.videoList = res.data || res || [];
      // 确保 DataTable 初始化后再更新数据
      if (!this.table) {
        this._initDataTable();
      } else {
        this._refreshTable();
      }
    } catch (err) {
      console.error("加载视频失败", err);
      this.videoList = [];
    }
  }

  _bindEvents() {
    this.videoModal = new bootstrap.Modal(
      this.dom.querySelector("#videoModal")
    );
    this.deleteConfirmModal = new bootstrap.Modal(
      this.dom.querySelector("#deleteConfirmModal")
    );
    const form = this.dom.querySelector("#videoForm");

    this.dom.querySelector("#btnAdd").addEventListener("click", () => {
      form.reset();
      form.querySelector("#videoId").value = "";
      this.dom.querySelector("#videoModalLabel").textContent = "新增视频";
      this.videoModal.show();
    });

    this.dom
      .querySelector("#saveUserBtn")
      .addEventListener("click", async () => {
        const id = form.querySelector("#videoId").value;
        const title = form.querySelector("#videoTitle").value;
        const content = form.querySelector("#videoContent").value;
        const link = form.querySelector("#videoLink").value;

        if (!title || !content || !link) {
          alert("请完整填写视频信息！");
          return;
        }

        const video = {
          videoTitle: title,
          videoContent: content,
          videoLink: link,
        };

        try {
          if (id) {
            await videoService.update(id, video);
          } else {
            await videoService.create(video);
          }
          this.videoModal.hide();
          await this._loadData();
          this._refreshTable();
        } catch (err) {
          alert("保存失败！");
          console.error(err);
        }
      });

    this.dom
      .querySelector("#confirmDeleteBtn")
      .addEventListener("click", async () => {
        if (this.pendingDeleteId !== null) {
          try {
            await videoService.remove(this.pendingDeleteId);
            this.pendingDeleteId = null;
            this.deleteConfirmModal.hide();
            await this._loadData();
            this._refreshTable();
          } catch (err) {
            alert("删除失败！");
            console.error(err);
          }
        }
      });
  }

  _initDataTable() {
    this.table = window
      .$(this.dom.querySelector("#basic-datatable"))
      .DataTable({
        data: this.videoList,
        lengthChange: false,
        pageLength: 10,
        destroy: true,
        autoWidth: false,
        ordering: true,
        searching: true,
        columns: [
          { data: "videoTitle" },
          { data: "videoContent" },
          {
            data: "videoLink",
            render: (data) => `<a href="${data}" target="_blank">查看</a>`,
          },
          {
            data: "createTime",
            render: (data) => data || "",
          },
          {
            data: "lastModifiedTime",
            render: (data) => data || "",
          },
          {
            data: null,
            orderable: false,
            render: (data, type, row) => {
              return `
              <button class="btn btn-sm btn-warning me-1 btn-edit" data-id="${row.videoId}">修改</button>
              <button class="btn btn-sm btn-danger btn-delete" data-id="${row.videoId}">删除</button>
            `;
            },
          },
        ],
      });

    // 每次刷新表格后重新绑定事件
    this._refreshTable();
  }

  _refreshTable() {
    if (this.table) {
      this.table.clear().rows.add(this.videoList).draw();
      this._bindRowEvents(); // 重新绑定行内按钮事件
    } else {
      console.error("DataTable未初始化");
    }
  }

  _bindRowEvents() {
    setTimeout(() => {
      const form = this.dom.querySelector("#videoForm");

      this.dom.querySelectorAll(".btn-edit").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          const id = e.target.dataset.id;
          const video = this.videoList.find((v) => v.videoId == id);
          if (!video) return;

          form.querySelector("#videoId").value = video.videoId;
          form.querySelector("#videoTitle").value = video.videoTitle;
          form.querySelector("#videoContent").value = video.videoContent;
          form.querySelector("#videoLink").value = video.videoLink;

          this.dom.querySelector("#videoModalLabel").textContent = "修改视频";
          this.videoModal.show();
        });
      });

      this.dom.querySelectorAll(".btn-delete").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          this.pendingDeleteId = e.target.dataset.id;
          this.deleteConfirmModal.show();
        });
      });
    }, 0);
  }
}
